package com.geek.javase.ch18.work.work1.version2;

import com.geek.javase.ch18.work.work1.Student;
import com.geek.javase.ch18.work.work1.Teacher;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.stream.Stream;

/*
 *@Date 2025/11/7
 *@Author wangpeng
 *@Description TODO
 */
public class ReflectObjectV2 {
    public static void main(String[] args) {
        Student student = new Student("张三", 101, 18);
        Teacher teacher = new Teacher("王朝", 10, "舞蹈");

        print(teacher);
        print(student);
    }
    public static void print(Object object) {
        try(
                PrintStream ps = new PrintStream(new FileOutputStream("obj.txt",true));
        ){
            //改变打印流的输出方向
            System.setOut(ps);

            //1.获取类类型
            Class<?> clazz = object.getClass();
            System.out.println("----------" + clazz.getSimpleName() + "+----------\n");

            //2.忽略其访问权限，获取所有属性
            Field[] fields = clazz.getDeclaredFields();
            Stream.of(fields).forEach(field -> {
                //3.取消访问权限检查
                field.setAccessible(true);
                try {
                    //4.将属性信息写至文件中  格式：属性名-属性值
                    System.out.println(field.getName() + "-" + field.get(object));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            });
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
